package org.jiuling.tencentcloud.cos.spring.handle;

import org.jiuling.tencentcloud.cos.TencentCloudCos;
import org.jiuling.tencentcloud.cos.config.TencentCosConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 腾讯云对象存储Spring处理
 * @author 紫灵
 * @date 2024年03月22日 22时33分55秒
 */
@Component
public class TencentCloudCosSpringHandle {

    /** 腾讯云对象存储 */
    private final TencentCloudCos tencentCloudCos;
    /** 腾讯云对象存储配置 */
    private final TencentCosConfig tencentCosConfig;

    public TencentCloudCosSpringHandle(TencentCloudCos tencentCloudCos, TencentCosConfig tencentCosConfig) {
        this.tencentCloudCos = tencentCloudCos;
        this.tencentCosConfig = tencentCosConfig;
    }

    /**
     * 通过spring文件上传
     * @param file 文件
     * @return 返回的key
     */
    public String uploudByMultipartFile(MultipartFile file) throws IOException {
        // 获取文件名称
        String iconFileName = file.getOriginalFilename();
        return tencentCloudCos.uploadObject(
                file.getInputStream(),
                file.getContentType(),
                tencentCosConfig.getBucketName(),
                "."+iconFileName.substring(iconFileName.lastIndexOf(".") + 1)
        );
    }

}
